package com.xcw.jac.multithreadeddownloader.core;

import com.xcw.jac.multithreadeddownloader.constant.Constant;

import java.util.concurrent.atomic.LongAdder;

/**
 * @author xcw
 * @date 2023/8/10 15:05
 * @description
 */
public class DownLoadInfoThread implements Runnable {

    // 下载文件总大小
    private Long httpFileContentLength;

    // 本地已经下载的大小[多线程原子类]
    public static LongAdder finishedSize = new LongAdder();

    // 前一次下载的大小
    public LongAdder prevSize = new LongAdder();


    // 本地累计下载文件大小
    public static volatile LongAdder  downSize = new LongAdder();

    public DownLoadInfoThread(Long contentLength) {
        this.httpFileContentLength = contentLength;
    }

    public DownLoadInfoThread() {
    }

    @Override
    public void run() {
        // 计算文件总大小 单位 MB
       String httpFileSize = String.format("%.02f", httpFileContentLength / Constant.MB);

        // 计算下载速度 单位 kb/s
        int speed = (int) ((downSize.doubleValue() - prevSize.doubleValue()) / 1024d);
        prevSize = downSize;

        // 剩余文件大小
        double remainSize  = httpFileContentLength - finishedSize.doubleValue() - downSize.doubleValue();

        // 计算剩余时间
        String remainTime = String.format("%.1f", remainSize / 1024d / speed);

        if ("Infinity".equalsIgnoreCase(remainTime)) {
            remainTime = "-";
        }

        // 计算已下载大小
        String currentFileSize = String.format("%.2f", (downSize.doubleValue() - finishedSize.doubleValue()) / Constant.MB);
        // 进制
        String downInfo = String.format("已下载 %smb/%smb,速度%skb/s,剩余时间 %ss", currentFileSize, httpFileSize, speed, remainTime);
        if (speed >= 1024d) {
            downInfo = String.format("已下载 %smb/%smb,速度%sm/s,剩余时间 %ss", currentFileSize, httpFileSize, String.format("%.1f", speed/1024d), remainTime);
        }
        System.out.println("\r");
        System.out.println(downInfo);
    }
}
